package cn.rengy.util;

public class _StrUtil {
    /**下划线**/
    private static final char underscore = '_';
    /**
     * 下划线转驼峰，
     * 如果原字符串有大写，不作处理，如user_nAme->userNAme
     * @param name
     * @return
     */
    public static String underscore2camelCase(String name) {
        if (name==null) {
            return "";
        }
        StringBuilder result = new StringBuilder(name.length());
        int length=name.length();
        for (int i = 0; i < length; i++) {
            char c = name.charAt(i);
            if (c==underscore&&i<length-1&&name.charAt(i+1)!=underscore&&!Character.isDigit(name.charAt(i+1))) {
                i++;
                c=name.charAt(i);
                result.append(Character.toUpperCase(c));
            }else {
                //如果是大写不做处理
                result.append(c);
            }
        }
        return result.toString();
    }

    /**
     * 驼峰转划线转，不处理首字母大写、尾字母大写、连续大写的情况，
     * 下划线跟着是数字也不处理
     * 如：UserName->_user_name, USERName->_u_s_e_r_name
     * @param name
     * @return
     */
    public static String camelCase2Underscore(String name) {
        if (name==null) {
            return "";
        }

        StringBuilder result = new StringBuilder(name.length());
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (Character.isUpperCase(c)) {
                result.append(underscore).append(Character.toLowerCase(c));
            }
            else {
                result.append(c);
            }
        }

        return result.toString();
    }

    /**
     * 如果包含下划线就返回驼峰格式，如果是驼峰就返回下划线格式，
     * @param name
     * @return
     */
    public static String reverse(String name){
        if (name==null) {
            return "";
        }
        StringBuilder result = new StringBuilder(name.length());
        int j=0;
        int length=name.length();
        for (int i = 0; i < length; i++) {
            char c = name.charAt(i);
            if (c==underscore&&i<length-1&&name.charAt(i+1)!=underscore&&!Character.isDigit(name.charAt(i+1))) {
                i++;
                c=name.charAt(i);
                result.append(Character.toUpperCase(c));
            }else if (Character.isUpperCase(c)) {
                result.append(underscore).append(Character.toLowerCase(c));
            }else {
                result.append(c);
            }
        }
        return result.toString();
    }


    public static void main(String[] args) {
        StringBuilder result = new StringBuilder(0);
        System.out.println(underscore2camelCase("zjrl_1005"));
        System.out.println(underscore2camelCase("id_"));
        System.out.println(reverse("user_nAme"));
        System.out.println(reverse("id_"));
    }
}
